//
//  SSDKPluginStringUtil.m
//  SSDKPlugin-demo
//
//  Created by 涂俊 on 2017/7/10.
//  Copyright © 2017年 涂俊. All rights reserved.
//

#import "SSDKPluginStringUtil.h"

@implementation SSDKPluginStringUtil

+ (BOOL)isEmptyString:(NSString *)string {
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+ (NSString *)URLEncodedString:(NSString *)str {
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)str,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

+ (NSString *)URLDecodedString:(NSString *)str {
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

//将dictionary转为表单参数拼接字符串
+ (NSString *)stringFromParams:(NSDictionary *)params {
    if (params == nil) {
        return @"";
    }
    NSMutableString *dataStr = [[NSMutableString alloc] init];
    for (NSString *key in params) {
        NSString * value = [params valueForKey:key];
        value = [self URLEncodedString:value];
        [dataStr appendString:key];
        [dataStr appendString:@"="];
        [dataStr appendString:value];
        [dataStr appendString:@"&"];
    }
    [dataStr deleteCharactersInRange:NSMakeRange(dataStr.length - 1, 1)];
    return dataStr;
}

//将表单参数拼接字符串转为dictionary
+ (NSDictionary *)paramsFromString:(NSString *)str {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    if ([self isEmptyString:str]) {
        return params;
    }
    NSArray<NSString *> *kvArray = [str componentsSeparatedByString:@"&"];
    for (NSString *kv in kvArray) {
        if (![self isEmptyString:kv]) {
            NSArray<NSString *> *pair = [kv componentsSeparatedByString:@"="];
            //将数据进行urldecode后返回
            NSString *value = [self URLDecodedString:[pair objectAtIndex:1]];
            [params setValue:value forKey:[pair objectAtIndex:0]];
        }
    }
    return params;
}

@end
